// stores/menuStore.ts
import { defineStore } from 'pinia';
import { Menu } from '@tauri-apps/api/menu';
import { LogicalPosition } from '@tauri-apps/api/window';

export const useMenuStore = defineStore('menu', {
  state: () => ({
    menu: null as Menu | null, // 当前的菜单
    isVisible: false, // 菜单是否可见
    position: { x: 0, y: 0 }, // 菜单显示的位置
  }),

  actions: {
    // 设置菜单项
    async setMenu(items: Array<{ id: string, text: string, action: () => void }>, position: { x: number, y: number }) {
      if (this.isVisible && this.menu) {
        // 如果菜单已经显示，先隐藏
        this.resetMenu();
      }

      this.isVisible = true;

      // 创建新的菜单
      const menu = await Menu.new({
        items: items.map(item => ({
          id: item.id,
          text: item.text,
          action: item.action,
        })),
      });

      this.menu = menu;
      this.position = position;


      // 显示菜单
      try {
        await menu.popup(new LogicalPosition(position.x, position.y));
      } finally {
        // 用户关闭菜单后重置
        this.isVisible = false;
        this.menu = null;
      }
    },

    // 隐藏菜单
    resetMenu() {
      this.isVisible = false;
      if (this.menu) {
        // 清理菜单
        this.menu = null;
      }
    },
  },
});
